﻿using Jinjia.Core.BaseInfrastructure.BaseModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace Jinjia.Approve.ScheduleJobAPI.Controllers.Base
{
    [Route("api/[controller]/[action]")]
    public abstract class BaseJobController : CoreBaseController
    {
        private static bool IsRunning { get; set; } = false;
        private readonly ILogger<BaseJobController> _logger;

        protected BaseJobController(ILogger<BaseJobController> logger)
        {
            _logger = logger;
        }

        [HttpGet("GetRunningStatus")]
        public IActionResult GetRunningStatus()
        {
            return Ok(IsRunning);
        }

        protected void RunScheduleJob(Action scheduleJobExecutor, Action<Exception> ExceptionHandler = default)
        {
            if (!IsRunning)
            {
                IsRunning = true;

                _ = Task.Run(() =>
                {
                    try
                    {
                        scheduleJobExecutor.Invoke();
                    }
                    catch (Exception e)
                    {
                        if (ExceptionHandler != default)
                        {
                            ExceptionHandler.Invoke(e);
                        }
                        else
                        {
                            _logger.LogError(e, "自动捕获异常,异常信息:{Message}", e.Message);
                        }
                    }
                    finally
                    {
                        IsRunning = false;
                    }
                });
            }
        }
    }
}